package com.example.floatingpopulation.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import com.example.floatingpopulation.controller.dto.chartsDTO;
import com.example.floatingpopulation.controller.request.BaseRequest;
import com.example.floatingpopulation.controller.request.FloatingPopulationPageRequest;
import com.example.floatingpopulation.entity.FloatingPopulation;
import com.example.floatingpopulation.mapper.FloatingPopulationMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class FloatingPopulationServiceImpl implements com.example.floatingpopulation.service.FloatingPopulationService {

    @Autowired
    FloatingPopulationMapper floatingPopulationMapper;
    @Override
    public List<FloatingPopulation> list() {
        return floatingPopulationMapper.list();
    }

    @Override
    public PageInfo<FloatingPopulation> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<FloatingPopulation> users = floatingPopulationMapper.listByCondition(baseRequest);
        return new PageInfo<>(users);
    }


    @Override
    public void save(FloatingPopulation obj) {
        floatingPopulationMapper.save(obj);
    }

    @Override
    public void update(FloatingPopulation obj) {
        obj.setUpdateTime(new Date());
        floatingPopulationMapper.updateById(obj);
    }

    @Override
    public void deleteById(Integer id) {
        floatingPopulationMapper.deleteById(id);
    }

    @Override
    public List<Dict> countFloatingPopulation() {
        List<chartsDTO> floatingPopulationList = floatingPopulationMapper.countFloatingPopulation();
        // 将每个 chartsDTO 转换为一个 Dict 对象
        List<Dict> result = floatingPopulationList.stream()
                .map(dto -> {
                    Dict dict = Dict.create(); // 创建一个 Dict 对象
                    dict.set("date", dto.getDate()); // 设置 date
                    dict.set("value", dto.getValue() != null ? dto.getValue() : 0); // 设置 value，处理 null 值
                    return dict;
                })
                .collect(Collectors.toList());
        return result;

    }
}
